<template>
  <div class="editor-container">
    <div id="editor-box"></div>
    <div class="bottom">
      <el-button type="primary" @click="onSubmitClick">{{
          $t('msg.article.commit')
        }}</el-button>
    </div>
  </div>
</template>

<script setup>
import E from 'wangeditor'
import { defineEmits, defineProps, onMounted, watch } from 'vue'
import i18next from 'i18next'
import { useStore } from 'vuex'
import { commitArticle, editArticle } from './commit'
// import { watchSwitchLang } from '@/utils/i18n'

const props = defineProps({
  title: {
    required: true,
    type: String
  },
  detail: {
    type: Object
  }
})
const emit = defineEmits(['onSuccess'])

const store = useStore()
// Editor实例
let editor
// 获取dom
let el
onMounted(() => {
  el = document.querySelector('#editor-box')
  initEditor()
})
const initEditor = () => {
  editor = new E(el)
  editor.config.zIndex = 1
  editor.config.showMenuTooltips = true
  editor.config.menuTooltipPosition = 'down'
  // 国际化
  editor.config.lang = store.getters.language === 'zh' ? 'zh-CN' : 'en'
  editor.i18next = i18next
  editor.create()
}

const onSubmitClick = async () => {
  if (props.detail && props.detail._id) {
    await editArticle({
      id: props.detail._id,
      title: props.title,
      content: editor.txt.html()
    })
  } else {
    await commitArticle({
      title: props.title,
      content: editor.txt.html()
    })
  }
  editor.txt.html('')
  emit('onSuccess')
}

// 数据回显
watch(() => props.detail, val => {
  if (val && val.content) {
    editor.txt.html(val.content)
  }
}, {
  immediate: true
})
</script>

<style lang='scss' scoped>
.editor-container {
  .bottom {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
